<template>
  <div class="login-page-wrapper">
    <!-- 加载动画 -->
    <div v-if="isLoading" class="flex justify-center items-center py-12 animate-fade-in">
      <LoadingAnimation />
    </div>
    
    <!-- 装饰元素 -->
    <div class="absolute top-20 left-10 w-32 h-32 rounded-full bg-gradient-to-r from-indigo-500/10 to-purple-500/10 blur-3xl pointer-events-none"></div>
    <div class="absolute bottom-20 right-10 w-40 h-40 rounded-full bg-gradient-to-r from-blue-500/10 to-indigo-500/10 blur-3xl pointer-events-none"></div>
    
    <!-- 装饰性图标 -->
    <div class="absolute top-10 right-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="star" />
    </div>
    <div class="absolute bottom-10 left-20 opacity-30 pointer-events-none">
      <DecorativeIcon type="lightning" />
    </div>
    <div class="absolute top-1/2 left-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="news" />
    </div>
    <div class="absolute top-1/3 right-5 opacity-30 pointer-events-none">
      <DecorativeIcon type="dot" />
    </div>
    
    <div v-if="!isLoading" class="login-container animate-fade-in">
      <div class="login-card">
        <div class="login-header">
          <div class="absolute -left-2 -top-2 w-8 h-8 rounded-full bg-indigo-500 opacity-10 blur-md"></div>
          <div class="absolute -right-1 -top-1 scale-75 opacity-50 pointer-events-none">
            <DecorativeIcon type="star" :animate="false" />
          </div>
          <h2 class="login-title">管理员登录</h2>
        </div>
        
        <div class="login-form login-form-wrapper">
          <el-form :model="loginForm" :rules="rules" ref="loginFormRef" class="login-form-container" label-position="top" :label-width="0">
            <!-- 使用统一的容器类包裹所有输入元素，确保一致的宽度和对齐 -->
            <div class="uniform-input-container">
              <div class="input-wrapper">
                <el-form-item prop="username" class="form-item-no-margin">
                  <el-input 
                    v-model="loginForm.username" 
                    placeholder="用户名" 
                    prefix-icon="el-icon-user"
                    class="login-input"
                    @keyup.enter="handleLogin"
                  />
                </el-form-item>
              </div>
              
              <div class="input-wrapper">
                <el-form-item prop="password" class="form-item-no-margin">
                  <el-input 
                    v-model="loginForm.password" 
                    type="password" 
                    placeholder="密码" 
                    prefix-icon="el-icon-lock"
                    class="login-input"
                    show-password
                    @keyup.enter="handleLogin"
                  />
                </el-form-item>
              </div>
              
              <div class="input-wrapper">
                <el-form-item class="form-item-no-margin">
                  <el-button 
                    type="primary" 
                    @click="handleLogin" 
                    class="login-button w-full"
                    :loading="loginLoading"
                  >
                    登录
                  </el-button>
                </el-form-item>
              </div>
            </div>
          </el-form>
          
          <div class="flex justify-between items-center mt-4">
            <NuxtLink 
              to="/" 
              class="back-link text-sm text-slate-500  hover:text-indigo-600  transition-colors duration-300"
            >
              返回首页
            </NuxtLink>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入必要的组件和API
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import LoadingAnimation from '~/components/LoadingAnimation.vue';
import DecorativeIcon from '~/components/DecorativeIcon.vue';

// 使用空布局
definePageMeta({
  layout: 'empty'
});

const router = useRouter()
const route = useRoute()
const isLoading = ref(true)
const loginLoading = ref(false)
const loginFormRef = ref(null)

const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
    // 已移除密码长度限制，允许任意长度的密码
  ]
}

// 页面加载和登录状态检查
onMounted(() => {
  isLoading.value = false
  
  // 检查是否已登录
  const storedUser = localStorage.getItem('currentUser')
  if (storedUser) {
    try {
      // 已登录：优先跳回 redirect 指定页面，否则到后台
      const redirect = route.query.redirect ? String(route.query.redirect) : ''
      if (redirect) {
        router.replace(redirect)
      } else {
        router.push('/admin/dashboard')
      }
    } catch (error) {
      console.error('Failed to parse user data:', error)
    }
  }
})

// 导入认证管理
import { useAuth } from '~/composables/useAuth'

const { login } = useAuth()

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loginLoading.value = true
      
      try {
        // 使用认证管理进行登录
        const result = await login(loginForm.value.username, loginForm.value.password)
        
        if (result.success) {
          // 登录成功
          ElMessage({
            message: '登录成功！',
            type: 'success'
          })

          // 登录成功后：优先跳回 redirect 指定页面，否则后台
          const redirect = route.query.redirect ? String(route.query.redirect) : ''
          if (redirect) {
            router.replace(redirect)
          } else {
            router.push('/admin/dashboard')
          }
        } else {
          // 登录失败
          ElMessage({
            message: result.error || '用户名或密码错误',
            type: 'error'
          })
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage({
          message: '登录失败，请重试',
          type: 'error'
        })
      } finally {
        loginLoading.value = false
      }
    } else {
      return false
    }
  })
}
</script>

<style scoped>
/* 表单容器样式 */
.login-form-container {
  padding: 0;
  width: 100%;
  --el-form-label-font-size: 0;
}

.login-form-wrapper {
  padding: 0;
  margin: 0;
  width: 100%;
}

/* 统一容器样式，确保所有输入元素对齐 */
.uniform-input-container {
  width: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}

.input-wrapper {
  padding: 0;
  margin: 0 0 20px 0;
  width: 100%;
}

.input-wrapper:last-child {
  margin-bottom: 0;
}
/* 表单项样式 */
:deep(.el-form-item) {
  margin-bottom: 20px; /* 增加表单项之间的间距 */
  padding: 0;
}

/* 无边距表单项 */
:deep(.form-item-no-margin) {
  margin: 0;
  padding: 0;
}

:deep(.form-item-no-margin .el-form-item__content) {
  margin: 0 !important;
  padding: 0 !important;
}

:deep(.el-form-item__content) {
  line-height: 44px; /* 与输入框高度一致 */
}

/* 调整表单项的左右边距，确保与按钮对齐 */
:deep(.el-form-item) {
  padding: 0;
}
/* 覆盖Element Plus输入框默认样式 */
:deep(.el-input__wrapper) {
  box-shadow: none !important;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: none !important;
}

/* 页面进入动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.login-page-wrapper {
  min-height: 100vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
  background-color: var(--light-bg);
  position: relative;
  overflow: hidden;
}


.login-container {
  width: 100%;
  max-width: 400px;
  animation: slideUp 0.6s ease-out;
}

.login-card {
  background-color: var(--light-card);
  border-color: var(--light-border);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.03), 0 1px 3px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  border-top: 3px solid var(--primary-color); /* 添加主题色边框 */
  transition: all 0.3s ease;
  animation: fadeIn 0.5s ease-out forwards;
  position: relative;
  overflow: hidden;
  padding: 2rem; /* 增加内边距 */
}

.login-card::before {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(79, 70, 229, 0.1) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.5s ease;
}

.login-card:hover::before {
  opacity: 1;
}



.login-header {
  margin-bottom: 1.5rem;
  position: relative;
}

.login-title {
  color: var(--light-text);
  font-weight: 600;
  font-size: 1.5rem;
  text-align: center;
  margin-bottom: 1rem;
}


.login-input :deep(.el-input__inner) {
  border-radius: 8px;
  transition: all 0.3s ease;
  border: 1px solid var(--light-border);
  -webkit-appearance: none;
  appearance: none;
  box-shadow: none;
  outline: none;
  height: 44px; /* 增加高度 */
  padding: 0 15px 0 35px; /* 调整水平内边距，为左侧图标留出空间 */
  font-size: 1rem; /* 调整字体大小 */
  width: 100% !important; /* 确保宽度占满 */
  box-sizing: border-box !important; /* 确保padding和border包含在宽度内 */
}


.login-input :deep(.el-input__inner:focus) {
  border-color: var(--primary-color);
  box-shadow: none !important;
  outline: none !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}


/* 覆盖Element Plus输入框默认样式 */
:deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: none !important;
  padding: 0 !important;
  background: transparent !important;
  margin: 0 !important; /* 确保没有外边距 */
  width: 100% !important; /* 确保宽度占满容器，使用!important确保优先级 */
  max-width: 100% !important; /* 限制最大宽度 */
  box-sizing: border-box !important; /* 确保padding和border包含在宽度内 */
  display: block !important; /* 确保元素是块级元素 */
  position: static !important; /* 确保元素使用正常的文档流定位 */
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: none !important;
  border: none !important;
}



/* 全局样式覆盖 */
.el-input, .el-input__wrapper {
  box-shadow: none !important;
  border: none !important;
}

.el-input__wrapper.is-focus, .el-input.is-focus .el-input__wrapper {
  box-shadow: none !important;
  border: none !important;
}

/* 特别针对左侧和前缀图标区域的样式覆盖 */
:deep(.el-input__prefix),
:deep(.el-input__prefix-inner),
:deep(.el-input__suffix),
:deep(.el-input__suffix-inner) {
  background: transparent !important;
  box-shadow: none !important;
  border: none !important;
}

/* 调整前缀图标的位置和大小 */
:deep(.el-input__prefix) {
  left: 10px !important; /* 固定左侧位置 */
  padding: 0 !important;
  position: absolute !important;
}

:deep(.el-input__prefix-inner i) {
  font-size: 18px; /* 增加图标大小 */
  color: var(--primary-color); /* 使用主题色 */
}


/* 确保输入框内所有元素都没有轮廓和阴影 */
:deep(.el-input *) {
  box-shadow: none !important;
  outline: none !important;
  -webkit-appearance: none !important;
  appearance: none !important;
}

/* 移除所有可能的边框和轮廓 */
.login-input :deep(*) {
  box-shadow: none !important;
  outline: none !important;
}

/* 确保输入框容器没有额外边距 */
.login-input {
  width: 100% !important;
  margin: 0 !important;
  padding: 0 !important;
  display: block !important;
  box-sizing: border-box !important;
}

/* 确保el-input组件也是100%宽度 */
:deep(.el-input) {
  width: 100% !important;
  box-sizing: border-box !important;
}

.login-button {
  border-radius: 8px;
  height: 44px; /* 与输入框高度一致 */
  font-weight: 500;
  transition: all 0.3s ease;
  background: linear-gradient(to right, #6366f1, #3b82f6);
  border: none;
  font-size: 1rem; /* 调整字体大小 */
  color: white;
}

.login-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  background: linear-gradient(to right, #4f46e5, #2563eb);
}

.login-button:active {
  transform: translateY(0);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}



.back-link {
  position: relative;
  display: inline-block;
}

.back-link::after {
  content: '';
  position: absolute;
  width: 0;
  height: 1px;
  bottom: 0;
  left: 0;
  background-color: var(--primary-color);
  transition: width 0.3s ease;
}

.back-link:hover::after {
  width: 100%;
}

</style>